<?php
namespace App\Http\Controllers\Index;

use App\Http\Controllers\Controller;
use App\Logic\Sms;
use App\Logic\Code;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\User;


class UserController extends Controller
{

    /**
     * @OA\Post(
     *     path="/user_edit",
     *     tags={"用户"},
     *     summary="键值对修改个人信息",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"key", "val"},
     *                 @OA\Property(property="key", type="string", description="字段名包括：nickname,name,phone,email,address"),
     *                 @OA\Property(property="val", type="string", description="值"),
     *                 @OA\Property(property="code", type="string", description="验证码"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function edit(Request $request)
    {
        $post_data = $request->all();

        $validateRule = [
            'key'                      => 'required',
            'val'                      => 'present',
            'code'                      => 'required',
        ];
        $errorMsg = [
            'key.required'                 => '非法操作',
            'val.present'                 => '非法操作',
            'code.required'                 => '请传入验证码',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }
        $scene = $request->path();
        $key = $this->user['phone'].'_code_'.$scene;

        $code_info = Code::code($key,$post_data['code']);
        if($code_info['status'] === 'ERROR'){
            return $code_info;
        }

        $array = [
            'nickname','name','phone','email','address'
        ];

        if(!in_array($post_data['key'],$array)) {
            return e_msg(300001,'要修改的字段不存在');
        }

        if($post_data['key'] == 'phone') {

            $exists_id = Db::table('user')->where('phone',$post_data['val'])->value('id');
            if($exists_id && $exists_id != $this->user['id']){
                return e_msg(123456,'该手机号已注册');
            }
        }
        $rel = Db::table('user')->where('id',$this->user['id'])->update([$post_data['key']=>$post_data['val']]);

        if($rel){
            return s_msg('');
        }else{
            return e_msg(3000015,'您未作出改变');
        }
    }

    /**
     * @OA\Post(
     *     path="/password",
     *     tags={"用户"},
     *     summary="修改密码",
     *     @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *      @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"password","code"},
     *                 @OA\Property(property="password", type="string", description="场景"),
     *                 @OA\Property(property="code", type="string", description="验证码"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function password(Request $request)
    {
        $post_data = $request->all();

        $validateRule = [
            'password'                      => 'required',
            'code'                          => 'required',
        ];
        $errorMsg = [
            'scene.required'                 => '新密码不能为空',
            'code.required'                  => '验证码不能为空',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }

        $scene = $request->path();
        $info = $this->user;
        $key = $info['phone'].'_code_'.$scene;

        $code_info = Code::code($key,$post_data['code']);
        if($code_info['status'] === 'ERROR'){
            return $code_info;
        }

        $new_password = User::password($post_data['password']);
        $rel = Db::table('user')->where('id',$info['id'])->update(['password'=>$new_password]);

        if($rel){
            Cache::forget($key);
            return s_msg('');
        }else{
            return e_msg(3000015,'您未作出改变');
        }

    }



    /**
     * @OA\Post(
     *     path="/userSend",
     *     tags={"用户"},
     *     summary="发送验证码(带token)",
     *     @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"scene"},
     *                 @OA\Property(property="scene", type="string", description="场景"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function user_send(Request $request){

        /**
         * phone
         * type
         * scene
         */
        $post_data = $request->all();

        $validateRule = [
            'scene'                          => 'required',
        ];
        $errorMsg = [
            'scene.required'                 => '场景不能为空',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }
//        $auth = self::$userModel::auth();
//        $info = $auth->user(); # JWT同样可以使用Auth门面的user方法
//        $post_data['phone'] = $info['phone'];
        $phone = $this->user['phone'];
        /**
         * 发送时存储 验证码  存储该验证码发送时间
         * 60s  判断发送间隔是否在60m之内
         */
        $code_key = $phone.'_code_'.$post_data['scene'];
        $time_key = $phone.'_time_'.$post_data['scene'];

        if (Cache::has($time_key)) {
            $send_time = Cache::get($time_key);
            if(time()-$send_time<60){
                return e_msg(300012,'每次发送间隔60秒');
            }
        }

//        else{
//            Cache::put($code_key, 123456, 600);
//            Cache::put($time_key, time(), 60);
//            return s_msg('发送成功（test,user),现在的验证码是123456');
//        }


        //cache($post_data['phone'] . 'code', 123456,120);
        //return s_msg('发送成功（test,collective),现在的验证码是123456');

        $random = mt_rand(100000, 999999);
        $content = '【指兴云】您的验证码是'.$random.',请注意查收(有效时间10分钟)';
        //$res = Sms::smsSend($post_data['phone'], $content);
        $res = Sms::smsSend($phone, $content);
        if($res['code'] === 200){
            Cache::put($code_key, $random, 600);
            Cache::put($time_key, time(), 60);
        }
        return $res;

    }

    /**
     * @OA\Post(
     *     path="/user_validation",
     *     tags={"用户"},
     *     summary="验证用户名称",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"user_name"},
     *                 @OA\Property(property="user_name", type="string", description="用户名称或手机号"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function validation(Request $request)
    {
        $post_data = $request->all();
        $validateRule = [
            'user_name' => 'required',

        ];
        $errorMsg = [
            'user_name.required' => '请传入用户名或手机号',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            return e_msg(300001, $errors[0]);
        }
        $user_info1 = Db::table('user')
            ->where('username', $post_data['user_name'])
            ->value('id');
        $user_info2 = Db::table('user')
            ->where('phone', $post_data['user_name'])
            ->value('id');

        $info = '';
        if($user_info1){
            $info = $user_info1;
        }
        if($user_info2){
            $info = $user_info2;
        }
        if ($info) {
            return s_msg('用户存在');
        } else {
            return s_msg('用户信息不存在');
        }
    }


}
